/*
 * @Author: Dorange.Wang
 * @Date: 2021-07-07 09:13:33
 * @LastEditors: your name
 * @LastEditTime: 2021-07-20 14:10:55
 * @Description: file content
 */
import storage from "store2";
import md5 from "md5";
import { arrayToTree } from "@/utils/util";
import { APP_TOKEN } from "@/utils/const";
import router from '@/router'
import {
  getHmuserUserbytoken,
  getHmuserAuth,
  postHmuserLogin,
} from "@/apis/app/HmUserController";

const state = {
  info: {},
  menus: [],
  menuTree: [],
};

const mutations = {
  setUserInfo(state, payload) {
    state.info = payload;
  },
  setUserMenus(state, payload) {
    state.menus = payload;
    state.menuTree = arrayToTree(payload, null);
  },
};

const actions = {
  async loadUserInfo({ commit }) {
    const info = await getHmuserUserbytoken();
    commit("setUserInfo", info);
  },

  async loadUserMenus({ commit }) {
    const menus = await getHmuserAuth();
    commit("setUserMenus", menus);
  },

  async userLogin(context, payload) {
    const { username, password } = payload;
    const params = {
      username,
      password: md5(password),
    };
    const token = await postHmuserLogin(params);
    storage.set(APP_TOKEN, token);
    return token
  },

  async userLogout({ commit }) {
    console.log('userLogout')
    commit("setUserInfo", {});
    commit("setUserMenus", []);
    storage.set(APP_TOKEN, '');
    router.push({
      path:'/user/login'
    })
    // window.location.reload()
  },
};

const getters = {
  userInfo(state) {
    return state.info;
  },
  userMenuTree(state) {
    return state.menuTree;
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};
